package com.futao.support;

import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;


/**
 * @author futao
 * Created on 18-6-8-上午9:28.
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {
    /**
     * 整个表达式可以分为五个部分：
     * <p>
     * 1、execution(): 表达式主体。
     * <p>
     * 2、第一个*号：表示返回类型， *号表示所有的类型。
     * <p>
     * 3、包名：表示需要拦截的包名，后面的两个句点表示当前包和当前包的所有子包，com.sample.service.impl包、子孙包下所有类的方法。
     * <p>
     * 4、第二个*号：表示类名，*号表示所有的类。
     * <p>
     * 5、*(..):最后这个星号表示方法名，*号表示所有的方法，后面括弧里面表示方法的参数，两个句点表示任何参数
     */
//    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) && @annotation(org.springframework.web.bind.annotation.RestController)")
//    @Pointcut("execution(public * com.futao.controller..* (..)) && @annotation(org.springframework.web.bind.annotation.RestController)")
    @Pointcut("execution(public * com.futao.controller.*.*(..))")
    public void pointCut() {

    }

    private Logger logger = Logger.getLogger(getClass());

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) throws IOException {
        logger.info("...................................");
        System.out.println("pointCut-Before....");
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        HttpSession session = request.getSession();
//        if (session.isNew()) {
//            response.getWriter().append("new" + session.getId());
//        } else {
//            response.getWriter().append("old" + session.getId());
//        }

//        response.setHeader("Location", "/users/ff80818163da0a4b0163da0a86150000");
        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));


    }

    @After("pointCut()")
    public void after() throws IOException, ServletException {
        System.out.println("pointCut-after...");
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("content-type", "text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
//        response.setHeader("Location", "/users/ff80818163da0a4b0163da0a86150000");
//        response.setHeader("content-type", "text/html;charset=UTF-8");

//        OutputStream outputStream = response.getOutputStream();
//        String data = "中国 China";
//        byte[] bytes = data.getBytes("utf-8");
//        outputStream.write(bytes);

        //获取headers
//        Enumeration<String> headers = request.getHeaders("Accept-Encoding");
//        if (headers.hasMoreElements()) {
//            System.out.println(headers.nextElement());
//        }
        //获取request中的参数
//        Map<String, String[]> requestParameterMap = request.getParameterMap();
//        requestParameterMap.forEach((k, v) -> {
//            System.out.println("--------");
//            System.out.println(k);
//            System.out.println(Arrays.toString(v));
//        });

        //response重定向
//        System.out.println(request.getRequestURL());
//        System.out.println(request.getRequestURI());
//        if (request.getRequestURI().equals("/users/"))
//            response.sendRedirect("/swagger-ui.html#/");
        //转发
//        if (request.getRequestURI().equals("/users/")) {
//            log.error("-----------====");
//            request.getRequestDispatcher("/swagger-ui.html#/").forward(request, response);

//        }

//        Cookie[] cookies = request.getCookies();
//        ServletOutputStream outputStream = response.getOutputStream();
//        if (cookies != null) {
////            outputStream.print("您上次访问本站的时间是：");
//            for (Cookie cooky : cookies) {
//                boolean lastVisitTime = cooky.getName().equals("lastVisitTime");
//                if (lastVisitTime) {
////                    outputStream.println(String.valueOf(cooky.getValue().getBytes("utf-8")));
//                }
//            }
//        }
//        Cookie cookie = new Cookie("lastVisitTime", "中" + DateTime.now().toString());
////        cookie.setDomain("/");
//        cookie.setMaxAge(24 * 60 * 60);
//        response.addCookie(cookie);

    }

    @AfterReturning(pointcut = "pointCut()")
    public void afterReturn() {
        System.out.println("pointCut-afterReturn...");
    }
}
